<template>
  <scroll-view
    :class="classes"
    :scroll-y="true"
    :upperThreshold="threshold"
    :lowerThreshold="threshold"
    @scrolltolower="scroll2lower"
    :scroll-with-animation="true"
    :enablePassive="true"
    :refresherEnabled="true"
    @refresherrefresh="onRefresherRefresh"
    :refresherTriggered="refresherTriggered"
    :enableBackToTop="true"
  >
    <div class="nut-infinite__container">
      <slot></slot>
    </div>

    <div class="nut-infinite__bottom">
      <template v-if="isInfiniting">
        <div class="nut-infinite__bottom-box">
          <slot name="loading">
            <slot name="loading-icon">
              <Loading
                class="nut-icon-loading nut-infinite__bottom-box__img"
              ></Loading>
            </slot>
            <div class="nut-infinite__bottom-box__text">
              {{ loadTxt || "加载中" }}
            </div>
          </slot>
        </div>
      </template>
      <template v-else-if="!hasMore">
        <slot name="finished">
          <div class="nut-infinite__bottom-tips">
            {{ loadMoreTxt || "加载更多" }}
          </div>
        </slot>
      </template>
    </div>
  </scroll-view>
</template>
<script lang="ts">
import { toRefs, reactive, computed, ref, nextTick } from "vue";
import { createComponent } from "./_part/create";
const { componentName, create } = createComponent("infinite-loading");

import { Loading } from "@nutui/icons-vue-taro";
import "./index.mini.scss";

const InfiniteLoading = create({
  props: {
    hasMore: {
      type: Boolean,
      default: true,
    },
    threshold: {
      type: Number,
      default: 200,
    },
    loadTxt: {
      type: String,
      default: "",
    },
    loadMoreTxt: {
      type: String,
      default: "",
    },
  },
  emits: ["scroll-change", "load-more", "refresh"],
  components: {
    Loading,
  },
  setup(props, { emit, slots }) {
    const state = reactive({
      beforeScrollTop: 0,
      isInfiniting: false,
    });

    const classes = computed(() => {
      const prefixCls = componentName;
      return {
        [prefixCls]: true,
      };
    });

    const scroll2lower = () => {
      // console.log("scroll2lower");
      state.isInfiniting = true;
      nextTick(() => {
        emit("load-more", () => {
          state.isInfiniting = false;
        });
      });
    };

    const refresherTriggered = ref(false);

    const onRefresherRefresh = () => {
      // console.log("onRefresherRefresh");
      if (refresherTriggered.value) return;
      refresherTriggered.value = true;
      emit("refresh", () => {
        refresherTriggered.value = false;
      });
    };

    return {
      classes,
      ...toRefs(state),
      slots,
      scroll2lower,
      onRefresherRefresh,
      refresherTriggered,
    };
  },
});

export default InfiniteLoading;
</script>
